import 'dart:async';
import 'dart:math';
import 'package:dio/dio.dart';
import '../models/account.dart';
import '../models/concert.dart';
import '../providers/ticket_hunter_provider.dart';
import '../utils/logger.dart';
import '../utils/device_utils.dart';
import 'signature_service.dart';
import 'behavior_simulation_service.dart';

class TicketHunterService {
  final Dio _dio = Dio();
  final SignatureService _signatureService = SignatureService();
  final BehaviorSimulationService _behaviorService = BehaviorSimulationService();
  
  static const String _baseUrl = 'https://mtop.damai.cn';
  static const String _orderBuildApi = '/h5/mtop.trade.order.build/4.0/';
  static const String _orderCreateApi = '/h5/mtop.trade.order.create/4.0/';
  static const String _itemDetailApi = '/h5/mtop.damai.item.detail/1.2/';

  TicketHunterService() {
    _setupDio();
  }

  void _setupDio() {
    _dio.options = BaseOptions(
      baseUrl: _baseUrl,
      connectTimeout: const Duration(seconds: 5),
      receiveTimeout: const Duration(seconds: 10),
      headers: {
        'Accept': 'application/json',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Accept-Encoding': 'gzip, deflate, br',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
      },
    );

    // 添加拦截器
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) async {
        // 添加随机延迟模拟人类行为
        await _behaviorService.randomDelay();
        
        AppLogger.debug('Ticket request: ${options.method} ${options.uri}');
        handler.next(options);
      },
      onResponse: (response, handler) {
        AppLogger.debug('Ticket response: ${response.statusCode}');
        handler.next(response);
      },
      onError: (error, handler) {
        AppLogger.error('Ticket request error: ${error.message}', error);
        handler.next(error);
      },
    ));
  }

  Future<HuntingResult> submitOrder({
    required Account account,
    required Concert concert,
    required TicketSku sku,
    required Map<String, dynamic> params,
  }) async {
    try {
      AppLogger.info('Submitting order for account: ${account.username}, sku: ${sku.name}');
      
      // 第一步：构建订单
      final buildResult = await _buildOrder(
        account: account,
        concert: concert,
        sku: sku,
        params: params,
      );

      if (!buildResult.success) {
        return HuntingResult(
          success: false,
          message: buildResult.message,
          timestamp: DateTime.now(),
          isBlocked: buildResult.isBlocked,
        );
      }

      // 第二步：创建订单
      final createResult = await _createOrder(
        account: account,
        concert: concert,
        sku: sku,
        buildData: buildResult.data!,
        params: params,
      );

      return HuntingResult(
        success: createResult.success,
        message: createResult.message,
        orderId: createResult.orderId,
        timestamp: DateTime.now(),
        isBlocked: createResult.isBlocked,
        metadata: {
          'buildResult': buildResult.data,
          'createResult': createResult.data,
        },
      );
    } catch (e) {
      AppLogger.error('Submit order failed', e);
      return HuntingResult(
        success: false,
        message: '提交订单异常: $e',
        timestamp: DateTime.now(),
      );
    }
  }

  Future<OrderBuildResult> _buildOrder({
    required Account account,
    required Concert concert,
    required TicketSku sku,
    required Map<String, dynamic> params,
  }) async {
    try {
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      
      final requestParams = {
        'itemId': concert.itemId,
        'skuId': sku.skuId,
        'quantity': sku.quantity,
        'exParams': jsonEncode({
          'channel': 'damai_app',
          'umpChannel': 'damai_app',
          'subChannel': 'damai',
          'atomSplit': '1',
          'serviceVersion': '2.0.0',
        }),
      };

      // 生成签名
      final signature = await _signatureService.generateSignature(
        params: requestParams,
        deviceId: account.deviceId,
        timestamp: timestamp,
      );

      final headers = await _buildHeaders(
        account: account,
        timestamp: timestamp,
        signature: signature,
        params: params,
      );

      // 模拟人类行为延迟
      await _behaviorService.simulateHumanBehavior('order_build');

      final response = await _dio.post(
        _orderBuildApi,
        data: requestParams,
        options: Options(headers: headers),
      );

      return _parseOrderBuildResponse(response);
    } catch (e) {
      AppLogger.error('Build order failed', e);
      return OrderBuildResult(
        success: false,
        message: '构建订单失败: $e',
      );
    }
  }

  Future<OrderCreateResult> _createOrder({
    required Account account,
    required Concert concert,
    required TicketSku sku,
    required Map<String, dynamic> buildData,
    required Map<String, dynamic> params,
  }) async {
    try {
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      
      final requestParams = {
        'itemId': concert.itemId,
        'skuId': sku.skuId,
        'quantity': sku.quantity,
        'buyNow': 'true',
        'exParams': jsonEncode({
          ...buildData,
          'channel': 'damai_app',
          'umpChannel': 'damai_app',
          'atomSplit': '1',
        }),
      };

      // 生成签名
      final signature = await _signatureService.generateSignature(
        params: requestParams,
        deviceId: account.deviceId,
        timestamp: timestamp,
      );

      final headers = await _buildHeaders(
        account: account,
        timestamp: timestamp,
        signature: signature,
        params: params,
      );

      // 模拟人类行为延迟
      await _behaviorService.simulateHumanBehavior('order_create');

      final response = await _dio.post(
        _orderCreateApi,
        data: requestParams,
        options: Options(headers: headers),
      );

      return _parseOrderCreateResponse(response);
    } catch (e) {
      AppLogger.error('Create order failed', e);
      return OrderCreateResult(
        success: false,
        message: '创建订单失败: $e',
      );
    }
  }

  Future<Map<String, String>> _buildHeaders({
    required Account account,
    required int timestamp,
    required String signature,
    required Map<String, dynamic> params,
  }) async {
    final userAgent = params['userAgent'] ?? await DeviceUtils.getUserAgent();
    final umid = await DeviceUtils.generateUmid(account.deviceId);
    
    final headers = <String, String>{
      'User-Agent': userAgent,
      'X-DEVICE-ID': account.deviceId,
      'X-T': timestamp.toString(),
      'X-APP-KEY': '12574478',
      'X-SIGN': signature,
      'X-UMID': umid,
      'X-FEATURES': '27',
      'X-APP-VER': '8.6.2',
      'X-LOCATION': '116.397128,39.916527',
      'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    };

    // 添加cookies
    if (account.cookies != null && account.cookies!.isNotEmpty) {
      final cookieString = account.cookies!.entries
          .map((e) => '${e.key}=${e.value}')
          .join('; ');
      headers['Cookie'] = cookieString;
    }

    // 添加设备指纹
    if (params['deviceFingerprint'] != null) {
      headers['X-MINI-WUA'] = params['deviceFingerprint'];
    }

    return headers;
  }

  OrderBuildResult _parseOrderBuildResponse(Response response) {
    try {
      if (response.statusCode != 200) {
        return OrderBuildResult(
          success: false,
          message: 'HTTP ${response.statusCode}',
        );
      }

      final data = response.data;
      final ret = data['ret'] as List?;
      
      if (ret != null && ret.isNotEmpty) {
        final retCode = ret[0] as String;
        
        if (retCode.startsWith('SUCCESS')) {
          return OrderBuildResult(
            success: true,
            message: '构建订单成功',
            data: data['data'],
          );
        } else {
          final message = ret.length > 1 ? ret[1] as String : retCode;
          final isBlocked = _isBlockedError(message);
          
          return OrderBuildResult(
            success: false,
            message: message,
            isBlocked: isBlocked,
          );
        }
      }

      return OrderBuildResult(
        success: false,
        message: '未知响应格式',
      );
    } catch (e) {
      return OrderBuildResult(
        success: false,
        message: '解析响应失败: $e',
      );
    }
  }

  OrderCreateResult _parseOrderCreateResponse(Response response) {
    try {
      if (response.statusCode != 200) {
        return OrderCreateResult(
          success: false,
          message: 'HTTP ${response.statusCode}',
        );
      }

      final data = response.data;
      final ret = data['ret'] as List?;
      
      if (ret != null && ret.isNotEmpty) {
        final retCode = ret[0] as String;
        
        if (retCode.startsWith('SUCCESS')) {
          final orderData = data['data'];
          return OrderCreateResult(
            success: true,
            message: '创建订单成功',
            orderId: orderData?['orderId'],
            data: orderData,
          );
        } else {
          final message = ret.length > 1 ? ret[1] as String : retCode;
          final isBlocked = _isBlockedError(message);
          
          return OrderCreateResult(
            success: false,
            message: message,
            isBlocked: isBlocked,
          );
        }
      }

      return OrderCreateResult(
        success: false,
        message: '未知响应格式',
      );
    } catch (e) {
      return OrderCreateResult(
        success: false,
        message: '解析响应失败: $e',
      );
    }
  }

  bool _isBlockedError(String message) {
    final blockedKeywords = [
      'RISK_CONTROL',
      'FREQUENCY_LIMIT', 
      'DEVICE_ABNORMAL',
      'ACCOUNT_RISK',
      'IP_BLOCKED',
      '风控',
      '限制',
      '异常',
      '封禁',
    ];
    
    return blockedKeywords.any((keyword) => 
        message.toUpperCase().contains(keyword.toUpperCase()));
  }

  Future<Map<String, dynamic>?> getItemDetail(String itemId) async {
    try {
      final timestamp = DateTime.now().millisecondsSinceEpoch;
      final deviceId = await DeviceUtils.generateDeviceId();
      
      final params = {'itemId': itemId};
      final signature = await _signatureService.generateSignature(
        params: params,
        deviceId: deviceId,
        timestamp: timestamp,
      );

      final headers = {
        'X-DEVICE-ID': deviceId,
        'X-T': timestamp.toString(),
        'X-APP-KEY': '12574478',
        'X-SIGN': signature,
      };

      final response = await _dio.get(
        _itemDetailApi,
        queryParameters: params,
        options: Options(headers: headers),
      );

      if (response.statusCode == 200) {
        final data = response.data;
        final ret = data['ret'] as List?;
        
        if (ret != null && ret.isNotEmpty && ret[0].toString().startsWith('SUCCESS')) {
          return data['data'];
        }
      }

      return null;
    } catch (e) {
      AppLogger.error('Get item detail failed', e);
      return null;
    }
  }
}

class OrderBuildResult {
  final bool success;
  final String message;
  final Map<String, dynamic>? data;
  final bool isBlocked;

  OrderBuildResult({
    required this.success,
    required this.message,
    this.data,
    this.isBlocked = false,
  });
}

class OrderCreateResult {
  final bool success;
  final String message;
  final String? orderId;
  final Map<String, dynamic>? data;
  final bool isBlocked;

  OrderCreateResult({
    required this.success,
    required this.message,
    this.orderId,
    this.data,
    this.isBlocked = false,
  });
}